<?php

namespace app\modules\api\controllers;

use Yii;
use yii\web\Controller;
use common\models\Tools;
use \common\models\Works;
use common\models\User;

/**
 * Default controller for the `api` module
 */
class WechatController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * 微信网页登录
     * url:/api/wechat/login
     */
    public function actionLogin()
    {
        $appid = Yii::$app->params['wechat_appid'];
        $wechat_redirect_url = Yii::$app->params['wechat_redirect_url'];
        
        $redirect_url = urlencode($wechat_redirect_url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_userinfo&state=xingelv#wechat_redirect";
        
        
        return $this->redirect($url);
//        $output['success'] = 1;
//        $output['msg'] = "请求成功！";
//        
//        $output['data'] = $data;
//        Tools::outputjson($output);
    }
    
    /**
     * 
     * url /api/wechat/login-second
     */
    public function actionLoginSecond(){
        $code = $_GET['code'];
        $state = $_GET['state'];
        $appid = Yii::$app->params['wechat_appid'];
        $appsecret = Yii::$app->params['wechat_appsecret'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        $data = file_get_contents($url);
        
        $data = json_decode($data);
        //print_r($data);exit;
        $access_token = $data->access_token;
        $openid = $data->openid;
        
//        echo $access_token;echo "<br/>";
//        echo $openid;
//        exit;
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $userdata = Tools::curl_get($userinfo_url);
        $userdata = json_decode($userdata);
        $openid = $userdata->openid;
        $nickname = $userdata->nickname;
        $sex = $userdata->sex;
        $headimgurl = $userdata->headimgurl;
        
        //检测该openid是否存在
        $exist = User::findOne(['openid'=>$openid]);
        if(!empty($exist)){//存在的直接登录
            //头像对比，更新
            if($exist->headimg != $headimgurl ){
                $exist->headimg = $headimgurl;
                $exist->save();
            }
            
            $login = Yii::$app->user->login($exist, 3600 * 24 * 30);
            $this->redirect('/');
        }else{//不存在的创建用户并登录
            $username_exist = User::findOne(['username'=>$nickname]);
            $username = empty($username_exist) ? $nickname : $nickname.time();
            
            $new_user = new \common\models\User();
            $new_user->username = $username;
            $new_user->headimg = $headimgurl;
            $new_user->gender = $sex;
            $new_user->openid = $openid;
            $new_user->setPassword($username);
            $new_user->generateAuthKey();
            if($new_user->save()){
                $login = Yii::$app->user->login($new_user, 3600 * 24 * 30);
                return $this->redirect('/');
            }
        }
    }
    
    public function actionValid(){
        $signature = $_GET['signature'];
        $token = 'xingelv';
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $echostr = $_GET['echostr'];

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode('', $tmpArr);
        $tmpStr = sha1( $tmpStr );
        if ($tmpStr == $signature) {
            echo $echostr;
        } else {
            echo '';
        }
    }
}
